package leetcode.editor.cn;
//给定一个字符串 s 和一个整数 k，从字符串开头算起，每计数至 2k 个字符，就反转这 2k 字符中的前 k 个字符。 
//
// 
// 如果剩余字符少于 k 个，则将剩余字符全部反转。 
// 如果剩余字符小于 2k 但大于或等于 k 个，则反转前 k 个字符，其余字符保持原样。 
// 
//
// 
//
// 示例 1： 
//
// 
//输入：s = "abcdefg", k = 2
//输出："bacdfeg"
// 
//
// 示例 2： 
//
// 
//输入：s = "abcd", k = 2
//输出："bacd"
// 
//
// 
//
// 提示： 
//
// 
// 1 <= s.length <= 10⁴ 
// s 仅由小写英文组成 
// 1 <= k <= 10⁴ 
// 
//
// Related Topics 双指针 字符串 👍 557 👎 0


//leetcode submit region begin(Prohibit modification and deletion)
class Solution230 {
    public String reverseStr1(String s, int k) {
        int count = 0;
        int start = 0;
        int length = s.length();
        StringBuilder str = new StringBuilder(s);
        for (int i = 0; i < length; i++) {
            count++;
            if (count == 2 * k) {
                reverseStrIndex1(str, start, start + k - 1);
                start = i + 1;
                count = 0;
            }
        }
        if (count > 0 && count < k) {
            reverseStrIndex1(str, start, length - 1);
        } else if (count >= k) {
            reverseStrIndex1(str, start, start + k - 1);
        }
        return str.toString();
    }

    private void reverseStrIndex1(StringBuilder s, int start, int end) {
        char c;
        while (start < end) {
            c = s.charAt(start);
            s.setCharAt(start, s.charAt(end));
            s.setCharAt(end, c);
            start++;
            end--;
        }
    }


    public String reverseStr(String s, int k) {
        int count = 0;
        int start = 0;
        int length = s.length();
        char[] chars = s.toCharArray();
        for (int i = 0; i < length; i++) {
            count++;
            if (count == 2 * k) {
                reverseStrIndex(chars, start, start + k - 1);
                start = i + 1;
                count = 0;
            }
        }
        if (count > 0 && count < k) {
            reverseStrIndex(chars, start, length - 1);
        } else if (count >= k) {
            reverseStrIndex(chars, start, start + k - 1);
        }
        return new String(chars);
    }

    private void reverseStrIndex(char[] chars, int start, int end) {
        char c;
        while (start < end) {
            c = chars[start];
            chars[start] = chars[end];
            chars[end] = c;
            start++;
            end--;
        }
    }

    public static void main(String[] args) {
        Solution230 s = new Solution230();
        System.out.println(s.reverseStr("abcdefg", 2));
    }
}
//leetcode submit region end(Prohibit modification and deletion)
